package com.lhwzs.user.servlets;

import com.google.gson.Gson;
import com.lhwzs.myssm.myspringmvc.BaseServlet;
import com.lhwzs.user.dao.IUserDAO;
import com.lhwzs.user.dao.impl.UserDAOImpl;
import com.lhwzs.user.pojo.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: 李燦
 * @Date: 2022/5/5 - 05 - 19:19
 * @Decsription: com.lhwzs.user.servlets
 * @version: 1.0
 */
@WebServlet("/user/*")
public class loginServlet extends BaseServlet {
    private IUserDAO dao = new UserDAOImpl();
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> result = new HashMap<>();
        request.setCharacterEncoding("utf-8");
        response.setContentType("test/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        HttpSession session = request.getSession();
        String serverVcode = (String) session.getAttribute("vCode");
        System.out.println("-----------------获取session:" + session.getId() + " " + serverVcode);
        // 校验前后端的验证码是否一致，不区分大小写
        if (serverVcode == null || !serverVcode.equalsIgnoreCase(vcode)) {
            result.put("code", -1);
            result.put("msg", "验证码输入错误");
        } else {
            // 登录逻辑处理
            User u = new User();
            u.setUsername(username);
            u.setPassword(password);
            // 访问数据库
            User query = dao.login(u);
            if (query != null) {// 登录成功
                result.put("code", 1);
                result.put("msg", "用户登录成功！");
                result.put("result", query);
            } else {// 登录失败
                result.put("code", 0);
                result.put("msg", "账号或密码错误！");
            }
        }
        response.getWriter().write(new Gson().toJson(result));
    }
}